package com.hxzy.servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @author nick
 */
@WebServlet("/doLogin")
public class LoginServlet extends HttpServlet {
    //测试用户名
    private final String USER_NAME = "admin";
    //测试密码
    private final String USER_PASSWORD = "123456";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("------------------doLogin接收到了表单提交的POST请求--------------------");

        //设置request请求的编码方式
        req.setCharacterEncoding("utf-8");

        //从request中获取所有url参数名称
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()) {//遍历
            //获取参数名称
            String parameter = parameterNames.nextElement();
            //根据参数名称获取对应的值
            String value = req.getParameter(parameter);
            System.out.println(parameter + " === " + value);
        }

        //获取用户名
        String userName = req.getParameter("userName");

        //获取密码
        String userPwd = req.getParameter("userPwd");

        if (userName.equals(USER_NAME) && userPwd.equals(USER_PASSWORD)) { //登录成功,跳转到data.jsp
            //resp.sendRedirect("data");
            RequestDispatcher requestDispatcher = req.getRequestDispatcher("/data");
            requestDispatcher.forward(req,resp);
        } else { //登录失败,返回登录页
            resp.sendRedirect("login.jsp");
        }
    }
}
